package org.wangbao.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.struts2.ServletActionContext;
import org.junit.Test;
import org.wangbao.model.Block;
import org.wangbao.model.News;
import org.wangbao.model.PubUrlArg;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.opensymphony.xwork2.ActionContext;

public class ContentParserService {

	List<News> resultList;

	HtmlParserUtil hpu;

	ActionContext ac;

	ServletContext sc;

	public ContentParserService() {

	}

	public String handleProjectPath() {
		ac = ActionContext.getContext();
		sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);

		return sc.getRealPath("/") + "WEB-INF/classes/";
	}

	public String handleWebPath() {
		ac = ActionContext.getContext();
		sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);

		// 此处需要注意 如果放置在程序目录下，将不可见，所以需要放置在WEB工程端
		return sc.getRealPath("/");
	}

	public String handleContextPath() {
		ac = ActionContext.getContext();
		sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);

		System.out.print(sc.getContextPath());
		return sc.getContextPath();

	}

	/**
	 * 根据关键字获得新闻链接和title
	 * 
	 * @param url
	 * @param keyword
	 * @return
	 * @throws Exception
	 */
	public HashMap getNewsTitle(String url, String keyword) throws Exception {

		hpu = new HtmlParserUtil(url, keyword);
		//resultList = hpu.parserTitle();
		HashMap hm = hpu.parserMapTitle();

		return hm;
	}

	public String getPaperContent(String url, String keyword) throws Exception {
		hpu = new HtmlParserUtil(url, keyword);
		resultList = hpu.parserContent();

		return toJsonNewsList();
	}

	private String handlePubUrl(String pubUrl) throws Exception {
		
		Gson gson = new Gson();
		Type type = new TypeToken<PubUrlArg>() {
		}.getType();

		PubUrlArg pub = gson.fromJson(pubUrl, type);
		Map<String,String> xx =pub.getConvertMap();
		String[] keys = (String[])xx.keySet().toArray();
		
		Block[] blockList = new Block[keys.length];

		for (int i = 0; i < keys.length; i++) {
			Block block = blockList[i];
			block.setJournalId(pub.getDstr());
			block.setVersionId(pub.getVstr());
			block.setBlockId(keys[i]);
			block.setPid(xx.get(keys[i]));
		}
		
		return gson.toJson(blockList, type);
	}
	
	
	private String handleTxtReplace(String blockConfig) throws Exception {
		Gson gson = new Gson();

		//System.out.print(blockConfig);

		Type type = new TypeToken<Block[]>() {
		}.getType();

		Block[] blockList = gson.fromJson(blockConfig, type);

		// 先进行字符替换，再进行文件写入
		BufferedReader reader = null;

		for (int i = 0; i < blockList.length; i++) {
			Block block = blockList[i];
			File file = new File(handleWebPath() + "ds/" + block.getJournalId()
					+ "/" + block.getVersionId() + "/" + block.getTextId());
			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), "GB2312"));
			StringBuffer sb = new StringBuffer();

			for (String line = null; (line = reader.readLine()) != null;) {
				sb.append(line);
			}
			block.setTextId(sb.toString());

			file = new File(handleWebPath() + "ds/" + block.getJournalId()
					+ "/" + block.getVersionId() + "/" + block.getTitleId());
			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), "GB2312"));
			sb = new StringBuffer();

			for (String line = null; (line = reader.readLine()) != null;) {
				sb.append(line);
			}

			block.setTitleId(sb.toString());
		}
		reader.close();
		return gson.toJson(blockList, type);
	}

	public String buildFlash(String blockConfig,String versionId,String journalId,String picPath) throws Exception {

		String rep = handleTxtReplace(blockConfig);
		String senpath = handleWebPath();
		String inpath = senpath + "genswf/src/genswf.mxml";
		String outpath = senpath + "genswf/src/exec.mxml";

		File file = new File(inpath);
		String charset = "utf-8";
		String line;

		try {
			FileInputStream tmpfis = new FileInputStream(inpath);
			InputStreamReader tmpisr = new InputStreamReader(tmpfis, Charset
					.forName(charset));
			BufferedReader tmpbr = new BufferedReader(tmpisr);

			FileOutputStream fos = new FileOutputStream(outpath);
			OutputStreamWriter osw = new OutputStreamWriter(fos, Charset
					.forName(charset));
			BufferedWriter bw = new BufferedWriter(osw);
			int lineNo = 0;
			System.out.println("AAAAAAAAAA---"+handleWebPath()+VersionControlService.getPicPath(journalId,versionId,picPath));

			while ((line = tmpbr.readLine()) != null) {
				lineNo++;
				if (line.contains("$[imgConfig]"))
					line = line.replace("$[imgConfig]", handleWebPath()+VersionControlService.getPicPath(journalId,versionId,picPath));
				if (line.contains("${blockConfig}"))
					line = line.replace("${blockConfig}", rep);
				if (line.contains("${linkConfig}"))
					line = line.replace("${linkConfig}", queryBlock(journalId,versionId));
				bw.write(line + "\r\n");
			}
			tmpbr.close();
			tmpisr.close();
			tmpfis.close();
			bw.close();
			osw.close();
			fos.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return outpath;
	}

	//按照新模式生成，包括 xmlURL等
	public String buildFlash2(String xmlURL,String pubUrl,String versionId,String journalId,String picPath) throws Exception {

		String rep = handlePubUrl(pubUrl);
		//String rep="";
		String senpath = handleWebPath();
		String inpath = senpath + "genswf/src/genswf.mxml";
		String outpath = senpath + "genswf/src/exec.mxml";

		File file = new File(inpath);
		String charset = "utf-8";
		String line;

		try {
			FileInputStream tmpfis = new FileInputStream(inpath);
			InputStreamReader tmpisr = new InputStreamReader(tmpfis, Charset
					.forName(charset));
			BufferedReader tmpbr = new BufferedReader(tmpisr);

			FileOutputStream fos = new FileOutputStream(outpath);
			OutputStreamWriter osw = new OutputStreamWriter(fos, Charset
					.forName(charset));
			BufferedWriter bw = new BufferedWriter(osw);
			int lineNo = 0;
			System.out.println("AAAAAAAAAA---"+handleWebPath()+VersionControlService.getPicPath(journalId,versionId,picPath));

			while ((line = tmpbr.readLine()) != null) {
				lineNo++;
				if (line.contains("$[imgConfig]"))
					line = line.replace("$[imgConfig]", picPath);
				if (line.contains("$[blockConfig]"))
					line = line.replace("$[blockConfig]", rep);
				if (line.contains("$[xmlURL]"))
					line = line.replace("$[xmlURL]", xmlURL);
				bw.write(line + "\r\n");
			}
			tmpbr.close();
			tmpisr.close();
			tmpfis.close();
			bw.close();
			osw.close();
			fos.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return outpath;
	}
	
	
	
	
	public void getNewsContent(News news) throws Exception {

		
		String content = hpu.getDetail(news.getHref());
		// add single page's indexBuild encapsulation
		news.setContent(content);
		
		// 将敏感词的计算和新闻内容的索引存储放置在提交处统一完成
		File2DocumentUtils fu = new File2DocumentUtils();
		List wordgroup = fu.querySensitiveWord();
		StringBuffer sensitiveWord = new StringBuffer();
		
		if (content!=null){
			for (int i=0;i<wordgroup.size();i++) {
				if (content.contains((String)wordgroup.get(i))){
					sensitiveWord.append((String)wordgroup.get(i)+";");
					content = content.replaceAll((String)wordgroup.get(i), "");
				}
			}
		}
		
		news.setSensitiveWord(sensitiveWord.toString());
	}


	private void buildIndex() {
		IndexBuilder ib = new IndexBuilder();
		try {
			ib.createIndex(resultList);
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public String toJsonNewsList(List<News> list) {

		Gson gson = new Gson();

		Type type = new TypeToken<List<News>>() {
		}.getType();
		String newsListToJson = gson.toJson(list, type);
		return newsListToJson;
	}
	
	
	public String toJsonNewsList() {

		Gson gson = new Gson();

		Type type = new TypeToken<List<News>>() {
		}.getType();
		String newsListToJson = gson.toJson(resultList, type);
		return newsListToJson;
	}

	public String toJsonNews(News news) {

		Gson gson = new Gson();
		String newsToJson = gson.toJson(news, News.class);
		return newsToJson;
	}

	@Test
	public void testJsonString() {

		ContentParserService cps = new ContentParserService();
		try {
			cps.getNewsTitle("http://news.baidu.com", "首开网店");
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/*
	 * 根据提交的Id,获得新的更全的NewsList对象保存
	 */
	public void saveBlock(String idGroup,HashMap<String,News> hm) {

		Gson gson = new Gson();
		Type type = new TypeToken<Block>() {
		}.getType();
		Block block = gson.fromJson(idGroup, type);
		List<News> newList = new ArrayList<News>();
		List<String> ids = block.getIdGroup();

		for (int i = 0; i < ids.size(); i++) {

			// 客户端获得的id应该与当前List对象保持一致
			News news = hm.get(ids.get(i));
			
			news.setJournalId(block.getJournalId());
			news.setBlockId(block.getBlockId());
			news.setVersionId(block.getVersionId());
			newList.add(news);
		}

		IndexBuilder ib = new IndexBuilder();
		try {
			ib.createIndex(newList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testQuery() throws CorruptIndexException, IOException{
		new ContentParserService().queryBlock("20100605","A03");
	}

	/**
	 * 当生成swf文件时需要根据journal,version 和block信息获取title和href 生成相关链接部分的内容
	 * 
	 * @param id
	 * @throws IOException
	 * @throws CorruptIndexException
	 */
	public String queryBlock(String journalId, String versionId)
			throws CorruptIndexException, IOException {
		// //生成时根据journalId 和versionId 遍历所有block ，获得的内容替换mxml文件部分；
		// //如何完成link-news在xml文件中的替换工作
		Term term1 = new Term("journal", journalId);
		Query query1 = new TermQuery(term1);

		Term term2 = new Term("version", versionId);
		Query query2 = new TermQuery(term2);

		BooleanQuery boolQuery = new BooleanQuery();
		boolQuery.add(query1, Occur.MUST);
		boolQuery.add(query2, Occur.MUST);

		IndexSearcher indexSearcher = new IndexSearcher(IndexBuilder.indexPath);
		Filter filter = null;
		TopDocs topDocs = indexSearcher.search(boolQuery, filter, 1000);
		System.out.println("总共有【" + topDocs.totalHits + "】条匹配结果");
		
		StringBuffer sb = new StringBuffer();
		
		List<News> blist = new ArrayList();

		for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
			int docSn = scoreDoc.doc; // 文档内部编号
			Document doc = indexSearcher.doc(docSn); // 根据编号取出相应的文档
			File2DocumentUtils.printDocumentInfo(doc); // 打印出文档信息
			
			News news = new News();
			news.setHref(doc.get("href"));
			news.setTitle(doc.get("title"));
			news.setBlockId(doc.get("block"));
			blist.add(news);

		}
		
		return toJsonNewsList(blist);
	}
	
	private String changePicPath(String picPath){
		return "";
	}

}
